﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Data;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using QuanLyKho.PhongLenh;
using QuanLyKho.PhongMau;

namespace QuanLyKho.Control
{
    public partial class Lss_Dangky : UserControl
    {
        public Lss_Dangky()
        {
            InitializeComponent();
            Loaddata();
            SetPropertiesGrid();
            SetPropertiesColumns();
        }

        public void Loaddata()
        {
            var tuNgay_gvSanPham = dtTuNgay_gvSanPham.Checked ? dtTuNgay_gvSanPham.Value.ToString("MM/dd/yyyy") : DateTime.Now.Month + "/01/" + DateTime.Now.Year;
            var denNgay_gvSanPham = dtDenNgay_gvSanPham.Checked ? dtDenNgay_gvSanPham.Value.ToString("MM/dd/yyyy") : DateTime.Now.Month + "/"
                + DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) + "/" + DateTime.Now.Year;
            gridSanPham.DataSource = DataAll.SelectAll("PhongMau_SanPham", "*", "WHERE (TrangThai = " + Convert.ToInt32(TrangThai.PhongMau_DuyetSanPham)
                + " OR TrangThai = " + Convert.ToInt32(TrangThai.PhongMau_PhongLenhDaNhan) + ") AND (CONVERT(DATE, NgayThang, 0) >= CONVERT(DATE,'"
                + tuNgay_gvSanPham + "', 0) AND CONVERT(DATE, NgayThang, 0) <= CONVERT(DATE,'" + denNgay_gvSanPham + "' , 0))");

            var tuNgay_gvLenh = dtTuNgay_gvLenh.Checked ? dtTuNgay_gvLenh.Value.ToString("MM/dd/yyyy") : DateTime.Now.Month + "/01/" + DateTime.Now.Year;
            var denNgay_gvLenh = dtDenNgay_gvLenh.Checked ? dtDenNgay_gvLenh.Value.ToString("MM/dd/yyyy") : DateTime.Now.Month + "/"
                + DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) + "/" + DateTime.Now.Year;

            var table = DataAll.SelectAll("LenhSanXuat inner join PhongMau_SanPham On LenhSanXuat.IdSanPham = PhongMau_SanPham.IdSanPham",
                "LenhSanXuat.[ID],PhongMau_SanPham.[MaHang] as MaSanPham,LenhSanXuat.[IdSanPham],[NgayLapLenh],[NguoiLapLenh],LenhSanXuat.[SoLuong],[NgayGuiLenh],[NgaySuaLenh],[NgayDuyetLenh],LenhSanXuat.[TrangThai],[NgayChungTu],[NgayHoachToan],LenhSanXuat.[SoChungTu],LenhSanXuat.[GhiChu],[KhoDen],[KhoDi],[SXTuNgay],[SXDenNgay]",
                "WHERE CONVERT(DATE, NgaySuaLenh, 0) >= CONVERT(DATE,'"
                + tuNgay_gvLenh + "', 0) AND CONVERT(DATE, NgaySuaLenh, 0) <= CONVERT(DATE,'" + denNgay_gvLenh + "' , 0)");

            var imconverter = new ImageConverter();
            var columns = new DataColumn("GuiLenh", typeof(byte[]));
            var columnsDelete = new DataColumn("Xoa", typeof(byte[]));
            columns.DefaultValue = imconverter.ConvertTo(Properties.Resources.export_gray, typeof(byte[]));
            columnsDelete.DefaultValue = imconverter.ConvertTo(Properties.Resources.DeleteIcon_Gray, typeof(byte[]));
            table.Columns.Add(columns);
            table.Columns.Add(columnsDelete);
            for (int i = 0; i < table.Rows.Count; i++)
            {
                if (Convert.ToInt32(table.Rows[i]["TrangThai"]) == Convert.ToInt32(TrangThai.LenhSanXuat_TaoMoi)
                    || Convert.ToInt32(table.Rows[i]["TrangThai"]) == Convert.ToInt32(TrangThai.LenhSanXuat_TuChoiDuyet))
                {
                    table.Rows[i]["GuiLenh"] = imconverter.ConvertTo(Properties.Resources.export, typeof(byte[]));
                    table.Rows[i]["Xoa"] = imconverter.ConvertTo(Properties.Resources.DeleteIcon, typeof(byte[]));
                }
            }
            gridLenh.DataSource = table;
        }

        public void SetPropertiesGrid()
        {
            gvLenh.BestFitColumns();
            gvLenh.FocusRectStyle = DrawFocusRectStyle.RowFullFocus;
            //gvLenh.Appearance.SelectedRow.BackColor = Color.Empty;
            //gvLenh.Appearance.SelectedRow.Options.UseBackColor = true;
            gvLenh.OptionsView.ShowGroupPanel = false;
            gvLenh.OptionsView.ShowFooter = true;
            gvLenh.OptionsFind.AlwaysVisible = true;
            gvLenh.Columns["ID"].Visible = false;

            gvSanPham.BestFitColumns();
            gvSanPham.FocusRectStyle = DrawFocusRectStyle.RowFullFocus;
            //gvSanPham.OptionsBehavior.Editable = false;
            gvSanPham.OptionsSelection.MultiSelect = true;
            gvSanPham.OptionsView.ShowGroupPanel = false;
            gvSanPham.OptionsView.ColumnAutoWidth = false;
            gvSanPham.OptionsView.ShowFooter = true;
            gvSanPham.OptionsFind.AlwaysVisible = true;
            gvSanPham.Columns["IdSanPham"].Visible = false;
            for (int i = 3; i < gvLenh.Columns.Count; i++)
            {
                gvLenh.Columns[i].OptionsColumn.AllowEdit = false;
            }
            for (int i = 3; i < gvSanPham.Columns.Count; i++)
            {
                gvSanPham.Columns[i].OptionsColumn.AllowEdit = false;
            }
        }

        public void SetPropertiesColumns()
        {
            gcGuiLenh.Width = 60;
            gcGuiLenh.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcMaSanPham.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcNgayLapLenh.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcNguoiLapLenh.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcSoLuong.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcNgaySuaLenh.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcTrangThai.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcNgayChungTu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcNgayHoachToan.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcSoChungTu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcGhiChu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
        }

        private void gvLenh_DoubleClick(object sender, EventArgs e)
        {
            if (gvLenh.FocusedRowHandle >= 0)
            {
                Lss_LapLenh.MaID = gvLenh.Columns["ID"].View.GetRowCellDisplayText(gvLenh.FocusedRowHandle, "ID");
                Lss_LapLenh.xem = Convert.ToInt32(gvLenh.GetDataRow(gvLenh.FocusedRowHandle)["TrangThai"]) == Convert.ToInt32(TrangThai.LenhSanXuat_TaoMoi)
                    || Convert.ToInt32(gvLenh.GetDataRow(gvLenh.FocusedRowHandle)["TrangThai"]) == Convert.ToInt32(TrangThai.LenhSanXuat_TuChoiDuyet);
                var lss = new Lss_LapLenh();
                lss.ShowDialog();
                Loaddata();
                Lss_LapLenh.MaID = "0";
            }
        }

        private void gvLenh_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "TrangThai")
            {
                e.DisplayText = Common.HienThiTrangThai(Convert.ToInt32(e.Value));
            }
        }

        private void gvSanPham_DoubleClick(object sender, EventArgs e)
        {
            if (gvSanPham.RowCount > 0)
            {
                var dataview = (DataView)gvSanPham.DataSource;
                var data = DataAll.SelectAll("HanhTrinh", "*", " WHERE SoChungTu='" + dataview[gvSanPham.FocusedRowHandle]["SoChungTu"]
                    + "' AND TrangThai=" + Convert.ToInt32(TrangThai.PhongMau_PhongLenhDaNhan));
                if (data.Rows.Count <= 0)
                {
                    DataAll.InsertAll("HanhTrinh", dataview[gvSanPham.FocusedRowHandle]["MaHang"]
                                + "," + Convert.ToInt32(PhongBan.PhongLenh)
                                + "," + dataview[gvSanPham.FocusedRowHandle]["SoChungTu"]
                                + "," + Convert.ToInt32(TrangThai.PhongMau_PhongLenhDaNhan)
                                + "," + Main.UserID
                                + "," + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")
                                + "," + dataview[gvSanPham.FocusedRowHandle]["SoLuong"]
                                + "," + Convert.ToDateTime(dataview[gvSanPham.FocusedRowHandle]["TuNgay"].ToString()).ToString("MM/dd/yyyy")
                                + "," + Convert.ToDateTime(dataview[gvSanPham.FocusedRowHandle]["DenNgay"].ToString()).ToString("MM/dd/yyyy"));
                    
                }
                Lss_LapLenh.IdSanPham = gvSanPham.Columns["IdSanPham"].View.GetRowCellDisplayText(gvSanPham.FocusedRowHandle, "IdSanPham");
                Lss_LapLenh.xem = true;
                var lss = new Lss_LapLenh();
                lss.ShowDialog();
                Loaddata();
                Lss_LapLenh.IdSanPham = "0";
                Lss_LapLenh.xem = false;
            }
        }

        private void gvLenh_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                GridView View = sender as GridView;
                string trangthai = View.GetRowCellDisplayText(e.RowHandle, View.Columns["TrangThai"]);
                if (trangthai == "Lệnh chờ duyệt")
                {
                    e.Appearance.BackColor = Color.SandyBrown;
                }
                else if (trangthai == "Lệnh không được duyệt")
                {
                    e.Appearance.BackColor = Color.Salmon;
                }
                else if (trangthai == "Tạo mới")
                {
                    e.Appearance.BackColor = Color.Empty;
                }
                else
                {
                    e.Appearance.BackColor = Color.DarkSeaGreen;
                }

            }
        }

        private void peGuiLenh_Click(object sender, EventArgs e)
        {
            var dataview = (DataView)gvLenh.DataSource;
            string a = gvLenh.GetRowCellValue(gvLenh.FocusedRowHandle, "TrangThai").ToString();
            string b = Convert.ToInt32(TrangThai.LenhSanXuat_TaoMoi).ToString();
            string c = Convert.ToInt32(TrangThai.LenhSanXuat_TuChoiDuyet).ToString();
            if (a == b || a == c)
            {

                DialogResult dialogResult = MessageBox.Show("Bạn có chắc chắn muốn gửi lệnh này.", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialogResult == DialogResult.Yes)
                {
                    string message = DataAll.Update("LenhSanXuat", "TrangThai =" + Convert.ToInt32(TrangThai.LenhSanXuat_ChoDuyet) + ",NgayGuiLenh ='" + DateTime.Now.ToString("MM/dd/yyyy") + "' WHERE ID =" + dataview[gvLenh.FocusedRowHandle]["ID"]);

                    MessageBox.Show(message.Equals("success") ? "Gửi lệnh thành công" : message, "Message",
                                        MessageBoxButtons.OK,
                                        message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    Loaddata();
                }
            }
        }

        private void gvSanPham_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "TrangThai")
            {
                e.DisplayText = Common.HienThiTrangThai(Convert.ToInt32(e.Value));
            }
        }

        private void gvSanPham_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == "DenNgay")
            {
                TimeSpan songay = Convert.ToDateTime(e.CellValue) - DateTime.Now;
                if (0 < songay.Days && songay.Days < 5)
                {
                    e.Appearance.BackColor = Color.PaleGoldenrod;
                }
                if (songay.Days < 0)
                {
                    e.Appearance.BackColor = Color.DarkGray;
                }
            }
        }

        private void dtTuNgay_gvSanPham_Leave(object sender, EventArgs e)
        {
            Loaddata();
        }

        private void dtDenNgay_gvSanPham_Leave(object sender, EventArgs e)
        {
            Loaddata();
        }

        private void dtTuNgay_gvLenh_Leave(object sender, EventArgs e)
        {
            Loaddata();
        }

        private void dtDenNgay_gvLenh_Leave(object sender, EventArgs e)
        {
            Loaddata();
        }

        private void peXoa_Click(object sender, EventArgs e)
        {
            var dataview = (DataView)gvLenh.DataSource;
            string a = gvLenh.GetRowCellValue(gvLenh.FocusedRowHandle, "TrangThai").ToString();
            string b = Convert.ToInt32(TrangThai.LenhSanXuat_TaoMoi).ToString();
            string c = Convert.ToInt32(TrangThai.LenhSanXuat_TuChoiDuyet).ToString();
            if (a == b || a == c)
            {

                DialogResult dialogResult = MessageBox.Show("Bạn có chắc chắn muốn xóa lệnh này.", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialogResult == DialogResult.Yes)
                {
                    string message = DataAll.Delete("LenhSanXuat", "ID = " + dataview[gvLenh.FocusedRowHandle]["ID"]);
                    message = DataAll.Update("PhongMau_SanPham", " TrangThai = " + Convert.ToInt32(TrangThai.PhongMau_DuyetSanPham) + " WHERE IdSanPham = " + dataview[gvLenh.FocusedRowHandle]["IdSanPham"]);
                    if (message.Equals("success"))
                    {
                        DataAll.Delete("LenhSanXuat_ChiTiet", "IDLenhSanXuat = " + dataview[gvLenh.FocusedRowHandle]["ID"]);
                    }
                    MessageBox.Show(message.Equals("success") ? "Xóa lệnh thành công" : message, "Message",
                                        MessageBoxButtons.OK,
                                        message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    Loaddata();
                }
            }
        }

        private void bntHuy_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var dataview = (DataView)gvSanPham.DataSource;
            string a = gvSanPham.GetRowCellValue(gvSanPham.FocusedRowHandle, "TrangThai").ToString();
            string b = Convert.ToInt32(TrangThai.PhongMau_DuyetSanPham).ToString();
            if (a == b)
            {
                DialogResult dialogResult = MessageBox.Show("Bạn có chắc chắn muốn hủy sản phẩm.", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialogResult == DialogResult.Yes)
                {
                    string message = DataAll.Update("PhongMau_SanPham", "TrangThai =" + Convert.ToInt32(TrangThai.PhongMau_ChoDuyet) + " WHERE IdSanPham =" + dataview[gvSanPham.FocusedRowHandle]["IdSanPham"]);

                    MessageBox.Show(message.Equals("success") ? "Hủy sản phẩm thành công" : message, "Message",
                                        MessageBoxButtons.OK,
                                        message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    Loaddata();
                }
            }
        }
    }
}
